<template>
  <div>
    <!-- 1、顶部导航模块   -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" style="margin-top: 0px; line-height: 10px">
      <el-form-item label="药品名称" ref="formRef" style="margin-left: 25px">
        <el-input v-model="formInline.name" placeholder="药品名称"></el-input>
      </el-form-item>
      <el-form-item label="所属科室">
        <el-select v-model="form.department" multiple placeholder="请选择药品所属科室">
          <el-option v-for="department in all_department" :label=department.name :value=department.id></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="select">查询</el-button>
        <el-button type="success" plain @click="newDepartment">新建药品</el-button>
        <el-button type="danger" plain @click="resetForm('formInline')">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 2、页面展示界面   -->
    <el-card class="box-card-departemt" style="margin-left: 25px">
      <el-table :data="deptTable" border style="width: 100%" text-align: right
                :cell-style="{ padding: '7px', 'text-align': 'center' }"
                @selection-change="handleSelectionChange"
                :row-class-name="tableRowClassName">
        <el-table-column type="selection" width="55" style="text-align: center"></el-table-column>
        <el-table-column fixed prop="id" label="序号"></el-table-column>
        <el-table-column prop="med_number" label="药品编码"></el-table-column>
        <el-table-column prop="name" label="药品名称" width="120"></el-table-column>
        <el-table-column prop="category" label="药品分类"></el-table-column>
        <el-table-column prop="department_name" label="所属科室"></el-table-column>
        <el-table-column prop="price" label="药物单价"></el-table-column>
        <el-table-column prop="ground_num" label="上架数量"></el-table-column>
        <el-table-column prop="is_ground_name" label="是否上架"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button el-button type="primary" icon="el-icon-edit" circle
                       @click="updateDepartment(scope.row),(drawer = true)"
                       size="small"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="deteleDepartment(scope.row)" size="small"
                       v-if="user_type !== '普通医生'"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 3、批量删除和分页栏    -->
    <div>
      <nobr style="margin-bottom: 20px">
        <div>
          <el-button type="danger" plain @click="batchDelete"
                     style="position: absolute; margin-left: 10px; margin-top: 25px; margin-bottom: 30px"
                     :disabled="multipleSelection.length === 0">批量删除
          </el-button>
          <!--          <el-button type="danger" plain @click="batchDelete"-->
          <!--                     style="position: absolute; margin-left: 25px; margin-top: 25px"-->
          <!--                     :disabled="multipleSelection.length === 0">批量删除-->
          <!--          </el-button>-->
        </div>

        <div class="course_pagination block">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="filter.page"
              :page-sizes="[2, 3, 5, 10]"
              :page-size="filter.size"
              layout="sizes, prev, pager, next"
              :total="course_total">
          </el-pagination>
        </div>
      </nobr>
    </div>


    <!-- 4、侧边栏导航 编辑药品   -->
    <el-drawer title="编辑药品" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px"
               style="position: absolute; margin-left: 30px; margin-top: 30px; width: 400px;">
        <el-form-item label="药品编号">
          <el-input v-model="form.med_number" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="药品名称">
          <el-input v-model="form.new_name" :placeholder=form.name></el-input>
        </el-form-item>
        <el-form-item label="药品分类">
          <el-input v-model="form.category" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="药物单价">
          <el-input v-model="form.new_price" :placeholder=form.price></el-input>
        </el-form-item>
        <el-form-item label="上架数量">
          <el-input-number v-model="form.new_ground_num" :placeholder=form.ground_num label="1"></el-input-number>
          <!--          <el-input v-model="form.ground_num"></el-input>-->
        </el-form-item>
        <el-form-item label="是否上架">
          <div>
            <el-radio v-model="is_ground_name" label="1" border>上架</el-radio>
            <el-radio v-model="is_ground_name" label="0" border>不上架</el-radio>
          </div>
          <!--          <el-input v-model="form.is_ground_name"></el-input>-->
        </el-form-item>
        <el-form-item label="所属科室">
          <el-select v-model="form.department" multiple placeholder="请选择药品所属科室">
            <el-option v-for="department in all_department" :label=department.name :value=department.id></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitDepartment">提交编辑</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
export default {
  // inject: ['reload'],
  data() {
    return {
      dept_list: [],
      course_total: 0,   // 当前总数量
      filter: {
        course_category: 0, // 当前用户选择的课程分类，刚进入页面默认为全部，值为0
        ordering: "orders",    // 数据的排序方式，默认值是orders，表示对于id进行降序排列
        size: 5,       // 单页数据量
        page: 1,
      },
      formInline: {
        name: "",
        category: "",
        deptType: "",
      },
      form: {
        id: "",
        med_number: "",
        name: "",
        deptType: "",
        category: "",
        price: "",
        ground_num: "",
        is_ground_name: "",
        new_price: "",
        new_ground_num: "",
        new_name: "",
        department_name: "",
        department: "",
      },
      user: {},
      // deptTable: [{
      //   'id': '1',
      //   'med_number': '001',
      //   'name': '假药',
      //   'category': '口服',
      //   'department_name': '假科室',
      //   'price': '1000000',
      //   'ground_num': '1',
      //   'is_ground_name': '已上架',
      // }],
      deptTable: [],
      multipleSelection: [],
      departmentClassification: [],
      departmentType: [],
      drawer: false,
      direction: "rtl",
      is_ground_name: "",
      all_department: [],
      user_type: '',
    };
  },
  // 1、 页面展示数据请求
  created() {
    // this.$axios.get(this.$settings.BASE_URL + 'user/department/').then(request => {
    //  # http://127.0.0.1:8000/api/v1/user/ke_name/
    this.$axios.get('http://127.0.0.1:8000/api/v1/user/ke_name/').then(request => {
      this.all_department = request.data
      console.log('----,我在这里01')
      // console.log(request.data, '---request数据')
      // console.log(this.all_department, '---all数据')
      console.log(this.all_department, '---count数据')
    })

    //axios查询全部药品列表请求
    // .get(this.$settings.BASE_URL + 'user/medicine/')
    this.$axios.get('http://127.0.0.1:8000/api/v1/user/yao/').then((Response) => {
      console.log(Response.data.results)
      // console.log('我在这哦02')
      this.deptTable = Response.data.results;
    })
        .catch((error) => {
          console.error(error);
        });
    // this.user = this.$getSessionStorage("user");
    this.user = 'kevin';
    // this.user_type = this.$getSessionStorage("user_type");
    this.user_type = '管理员';
    this.get_course();
  },
  watch: {
    // 监听属性
    // 监听筛选过滤和过滤，如果发生改变就重新加载页面数据
    "filter.course_category": function () {
      this.filter.page = 1;
      this.get_course();
    },
    "filter.ordering": function () {
      this.get_course();
    },
    "filter.size": function () {
      this.get_course();
    },
    "filter.page": function () {
      this.get_course();
    }
  },
  methods: {
    reload() {
      // 重新加载页面的逻辑
      window.location.reload();
    },

    handleSizeChange(val) {
      // 每页数据量发生变化时执行的方法
      this.filter.page = 1;
      this.filter.size = val;
    },
    handleCurrentChange(val) {
      // 页码发生变化时执行的方法
      this.filter.page = val;
    },
    updateDepartment(row) {
      if (this.user_type === "药管师" || '管理员') {
        console.log(row.id);
        this.form = row;
        console.log(this.form, '=++== 开始编辑')
      } else {
        this.$message({
          message: "很抱歉,您没有权限编辑药品",
          type: 'warning',
          duration: 1000
        })
      }
    },
    submitDepartment() {
      // this.user = this.$getSessionStorage("user");
      //axios编辑药品请求
      let _this = this
      let id = this.form.id
      const list = []
      for (let i = 0; i < this.form.department.length; i++) {
        list.push(this.form.department[i])
      }
      // console.log(this.form.new_ground_num, '----1 上架的数量')
      // console.log(this.is_ground_name, '----2，是否上架')
      console.log(this.form.name, typeof this.form.new_name, '--查看name属性')
      console.log(this.form.new_ground_num, '------ground_num上架数量====数据01')
      console.log(this.is_ground_name, '------====is_ground是否上架数据02')
      console.log(this.form.total, '------====total数据03')
      // this.$axios.put(this.$settings.BASE_URL + `user/medicine/${id}/`, {
      this.$axios.put(`${this.$settings.BASE_URL}user/yao/${this.form.id}/`, {
        med_number: this.form.med_number,
        price: this.form.new_price,
        total: this.form.total,
        ground_num: this.form.new_ground_num,
        name: this.form.new_name,
        is_ground: this.is_ground_name,
        category: this.form.category,
        department: list
        // data: data
      }).then((Response) => {
        this.$message({
          message: '编辑成功',
          type: 'success',
          duration: 1000
        })
        window.setTimeout(function () {
          _this.reload();
        }, 2000)
      }).catch((error) => {
        console.error(error);
        alert("编辑药品失败");
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
          .then((_) => {
            done();
          })
          .catch((_) => {
          });
    },
    // 单条删除
    deteleDepartment(row) {
      if (this.user_type === "药管师" || '管理员') {
        this.$confirm("确认删除此药品？").then((_) => {
              console.log(row.id);
              //axios通过id删除药品
              // this.$axios.delete(this.$settings.BASE_URL + `user/medicine/${row.id}/`).then((Response) => {
              this.$axios.delete(`${this.$settings.BASE_URL}user/yao/${row.id}/`).then((Response) => {
                this.$message({
                  message: `删除药物${this.form.name}成功`,
                  type: 'success',
                  duration: 1000
                })
                window.setTimeout(function () {
                  location.reload();
                }, 2000)
              }).catch((error) => {
                console.error(error);
                this.$message({
                  message: '删除失败',
                  type: 'warning',
                  duration: 1000
                })
              });
            }
        )
            .catch((_) => {
            });
      } else {
        this.$message({
          message: '很抱歉，你没有权限删除药物',
          type: 'warning',
          duration: 1000
        })
      }
    },
    resetForm(formName) {
      location.reload();
    },
    newDepartment() {
      if (this.user_type === "药管师" || '管理员') {
        this.$router.push({
          path: "/index/newDrug",
        });
      } else {
        alert("很抱歉,您没有权限新建药品");
      }
    },
    batchDelete() {
      if (this.user_type === "药管师" || '管理员') {
        if (this.multipleSelection.length === 0) {
          alert("至少选择一条数据进行批量删除");
        } else {
          console.log(this.multipleSelection, '----....01')
          console.log(this.multipleSelection.id, '----....02')
          this.$confirm("确认批量删除药品？")
              .then((_) => {
                //axios批量删除请求
                for (let dict of this.multipleSelection) {
                  console.log(dict.id, '---数据到这里了')
                  // this.$axios.delete(this.$settings.BASE_URL + `user/medicine/${dict.id}/`,).then((Response) => {
                  this.$axios.delete(`${this.$settings.BASE_URL}user/yao/${dict.id}/`).then((Response) => {
                    this.$notify({
                      title: '成功',
                      message: '批量删除成功',
                      type: 'success',
                    })
                    this.reload()
                  }).catch((error) => {
                    console.error(error);
                  });
                }
              })
              .catch((_) => {
              });
        }
      } else {
        this.$message({
          message: "很抱歉,您没有权限批量删除药品",
          type: 'warning',
          duration: 1000
        })
      }
    },
    //  2、分页排序请求
    get_course() {
      // 排序
      // console.log(this.deptTable, '---===到这里找#￥？')
      // let filters = {ordering: this.filter.ordering};
      let filters = {ordering: this.filter.ordering};
      // 判决是否进行分类课程的展示
      if (this.filter.course_category > 0) {
        filters.course_category = this.filter.course_category;
      }
      // 设置单页数据量
      if (this.filter.size > 0) {
        filters.size = this.filter.size;
      } else {
        filters.size = 5;
      }

      // 设置当前页码
      if (this.filter.page > 1) {
        filters.page = this.filter.page;
      } else {
        filters.page = 1;
      }
      // console.log(filters, '---===到这里查看分页01')
      // console.log(filters.ordering, '---===到这里查看分页02')
      // console.log(filters.page, '---===到这里查看分页03')
      // console.log(filters.size, '---===到这里查看分页04')
      // 获取药品列表信息
      // this.$axios.get(this.$settings.BASE_URL + 'user/medicine/', {
      // this.$axios.get('http://127.0.0.1:8000/api/v1/user/yao/?ordering=id&size=5&page=2', {
      // this.$axios.get('http://127.0.0.1:8000/api/v1/user/yao/?ordering=id', {params: filters}).then(response => {
      // this.$axios.get('http://127.0.0.1:8000/api/v1/user/yao/?ordering=id&page=${page}&page_size=${size}').then(response => {
      this.$axios.get(`${this.$settings.BASE_URL}user/yao/?ordering=id&page=${this.filter.page}&page_size=${this.filter.size}`).then(response => {
        // console.log(response.data, '---===到这里了01')
        this.deptTable = response.data.results;
        this.course_total = response.data.count;
        // console.log(response.this.deptTable, '---===到这里了01')
        // console.log(response.this.course_total, '---===到这里了02')
      }).catch(() => {
        // this.$message({
        //   // message: "获取课程信息有误，请联系客服工作人员"
        // })
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    //  3、搜索过滤请求
    select() {
      const department = []
      console.log(this.all_department, '开始搜索====、、、')
      for (let i = 0; i < this.form.department.length; i++) {
        department.push(this.form.department[i])
      }
      console.log(department, '开始搜索01====、、、')
      let name = this.formInline.name
      console.log(name, '开始搜索02====、、、')
      if (name.length === 0 || department.length === 0) {
        this.$message({
          message: '请在框中输入或选择内容',
          type: 'warning',
          duration: 1000
        })
      } else {
        console.log(department, '----123，这里')
        //  http://127.0.0.1:8000/api/v1/user/yao/?name=阿莫西林
        // this.$axios.get(this.$settings.BASE_URL + `user/medsearch/?name=${name}` + '&' + `department=${department}`).then(response => {
        this.$axios.get(`${this.$settings.BASE_URL}user/medsearch/?name=${name}&department=${department}`).then(response => {
          this.deptTable = response.data
        }).catch(() => {
          this.$message({
            message: '出现异常',
            type: 'warning',
            duration: 1000
          })
        })
      }

    },

    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    }
  },
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card-departemt {
  width: 1600px;
}

.el-main {
  line-height: 0px;
}

.course_pagination {
  margin-top: 60px;
  text-align: center;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #909399;
}
</style>






